package cs342.uwosh.group1.mycontacts.Threads;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

import cs342.uwosh.group1.mycontacts.Setup;

import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.util.Log;

public class CreateUserOnCloud extends AsyncTask<String, Object, String>{
	@Override
	protected String doInBackground(String...urls){
		
		String username = urls[0];
		String password = urls[1];

		URL url;
		String urlParameters="";
		try {
			urlParameters = "?username='"+URLEncoder.encode(username, "UTF-8")+"'&password='"+URLEncoder.encode(password, "UTF-8")+"'";
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		HttpURLConnection connection = null;
		try {
			//Setup connection
			url = new URL("http://softeng.cs.uwosh.edu/students/smithk58/project2/createUser.php"+urlParameters);
			connection = (HttpURLConnection)url.openConnection();
			connection.setRequestMethod("POST");
			connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
            connection.setRequestProperty("Content-Language", "en-US");
	        connection.setDoInput(true);
	        connection.setDoOutput(true);
	        connection.setUseCaches(false);
			
	        //Send request
	        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
	        wr.writeBytes(urlParameters);
	        wr.flush();
	        wr.close();
	        
	        //Get Response (should be the users id in this case, which needs to be stored in preferences)
	        InputStream is = connection.getInputStream();
	        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
	        String line;
	        StringBuffer response = new StringBuffer(); 
	        while((line = rd.readLine()) != null) {
	          response.append(line);
	        }
	        rd.close();
	        return response.toString();
	        
		} catch (MalformedURLException e) {
			return "Bad URL";
		} catch (IOException e) {
			return "Unable to retrieve web page";
		}
		finally
        {
            if(connection != null)
              connection.disconnect();
        }
	}
	@Override
	protected void onPostExecute(String result){
		
		
	}
}
